#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>

#include "server_socket.c"

#define SERVERPORT 3333 //定义端口号
#define BACKLOG 10 //请求队列中允许的最大请求数
#define MAXDATASIZE 50 //数据长度

// 字母大小写转换
char process_char(char c) {
    if (c >= 'a' && c <= 'z') {
        return c - 32;
    } else if (c >= 'A' && c <= 'Z') {
        return c + 32;
    }
    return c;
}


int main() {
    struct sockaddr_in cs;
    int c_size, recvbytes;
    int listen_socket_fd, client_fd; 
    char buf[MAXDATASIZE];
    int i;

	listen_socket_fd = tcp_listen_socket(SERVERPORT);	

	fd_set rfds, readmask;
	int retval;
	
	FD_ZERO(&rfds);
    FD_SET(listen_socket_fd, &rfds);

	for (;;) {
		readmask = rfds;
        retval = select(listen_socket_fd + 1, &readmask, NULL, NULL, NULL);
		
		if (FD_ISSET(listen_socket_fd, &readmask)) {
    		if((client_fd = accept(listen_socket_fd, (struct sockaddr *) &cs, &c_size)) == -1) {
        		perror("accept");
        		exit(1);
    		}
			
    		printf("accept success! fd = %d\n", client_fd);
    		
			// 读取客户端数据（阻塞 I/O）
			if((recvbytes = read(client_fd, buf, MAXDATASIZE)) == -1) {
        		perror("read error");
        		exit(1);
    		}
			
			// 关闭客户端连接
			if (recvbytes == 0) {
				close(client_fd);
				continue;
			}		
			
			// 处理数据
			for (i = 0; i < recvbytes; i++) {
				buf[i] = process_char(buf[i]);
			}
			
			// 阻塞写
			write(client_fd, buf, recvbytes);

			// 清空 buf
			memset(buf, 0x00, sizeof(buf));
		}
	}
	// 7. 关闭服务端 server socket
    close(listen_socket_fd);
}
